package com.ncu.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.ncu.web.entry.*;
import com.ncu.web.service.MajorityService;
import com.ncu.web.service.ContactsService;
import com.ncu.web.util.Code;
import com.ncu.web.util.JWTUtil;
import com.ncu.web.util.Util;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ncu.web.service.AdminService;
import com.ncu.web.service.UserService;

import java.sql.Timestamp;
import java.util.*;

/**
 * @Author:pwq
 * @Date:2024/5/28 9:20 web
 */



@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ContactsService contactsService;

    @Autowired
    private MajorityService majorityService;

    @Autowired
    private JWTUtil jwtUtil;

    @GetMapping("/user/login")
    @ResponseBody
    public String login(HttpServletRequest request,@RequestParam String id, @RequestParam String password) {
        if (id.equals("admin")) {
            Admin admin = adminService.selectAdminById(id);
            if (admin.getPassword().equals(password)) {
                String token = jwtUtil.createToken(id);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Code.LOGIN_SUCCESS);
                jsonObject.put("msg", "登录成功");
                jsonObject.put("token", token);
                return jsonObject.toJSONString();
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Code.ACCOUNT_OR_PASSWORD_ERROR);
                jsonObject.put("msg", "密码错误");
                return jsonObject.toJSONString();
            }
        } else {
            Student stu = userService.selectStudentById(id);
            if (stu == null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Code.NOT_REGISTER);
                jsonObject.put("msg", "该用户未注册");
                return jsonObject.toJSONString();
            } else if(stu.getPassword().equals(password)){
                if(stu.getPermission() == 0){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", Code.USER_OP_FAIL);
                    jsonObject.put("msg", "账号未通过审核，无法登录");
                    return jsonObject.toJSONString();
                }else{
                    stu.setLoginTimes((stu.getLoginTimes() + 1));
                    if (stu.getLastLoginTime() == null) {
                        stu.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
                        userService.updateLastLoginTime(id, stu.getLastLoginTime());
                    }
                    userService.updateLoginTimes(id, stu.getLoginTimes());
                    String token;
                    String oldToken = "";
                    String header = request.getHeader("Authorization");
                    if (header != null && header.startsWith("Bearer ")) {
                        oldToken = header.substring(7);
                        if (!jwtUtil.validateToken(oldToken)) {
                            token = jwtUtil.createToken(id);
                        } else {
                            token = oldToken;
                        }
                    } else {
                        token = jwtUtil.createToken(id);
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", Code.LOGIN_SUCCESS);
                    jsonObject.put("msg", "登录成功");
                    jsonObject.put("token", token);
                    return jsonObject.toJSONString();
                }
            }else{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Code.ACCOUNT_OR_PASSWORD_ERROR);
                jsonObject.put("msg", "密码错误");
                return jsonObject.toJSONString();
            }
        }
    }

    @GetMapping("/user/logoff")
    @ResponseBody
    public String logoff(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);;
        String id = jwtUtil.parseToken(token).getBody().get("username", String.class);
        Timestamp lastLoginTime = new Timestamp(jwtUtil.parseToken(token).getBody().getIssuedAt().getTime());
        JSONObject jsonObject = new JSONObject();

        if (userService.updateLastLoginTime(id, lastLoginTime) == 1) {
            //todo:redis实现jwt黑名单
            jsonObject.put("code", Code.USER_OP_SUCCESS);
            jsonObject.put("msg", "退出成功");
            return jsonObject.toJSONString();
        } else {
            jsonObject.put("code", Code.USER_OP_FAIL);
            jsonObject.put("msg", "退出失败");
            return jsonObject.toJSONString();
        }
    }

    @PostMapping("/user/register")
    @ResponseBody
    public String register(@RequestParam String id,@RequestParam String name,@RequestParam String password,@RequestParam int class_num,
                           @RequestParam int entry_year,@RequestParam int graduate_year,@RequestParam String employers,@RequestParam String city,
                           @RequestParam long phone,@RequestParam String email,@RequestParam int majority){
        if(id.equals("admin")){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", Code.USER_OP_FAIL);
            jsonObject.put("msg", "此ID不允许注册");
            return jsonObject.toJSONString();
        }else{
            Student student_1 = userService.selectStudentById(id);
            if(student_1 == null){
                Student student_2 = userService.selectStudentByPhone(phone);
                if (student_2 == null){
                    Student student_3 = userService.selectStudentByEmail(email);
                    if (student_3 == null){
                        //筛选完毕进行后续操作......
                        Contacts contacts = userService.insertContactsInformation(class_num, entry_year, graduate_year, employers, city, phone, email, majority);
                        if (userService.insertStudentInformation(id, password, contacts, name) != 0){
                            String token = jwtUtil.createToken(id);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("code", Code.USER_OP_SUCCESS);
                            jsonObject.put("msg", "注册成功");
                            return jsonObject.toJSONString();
                        }
                    }else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", Code.USER_OP_FAIL);
                        jsonObject.put("msg", "该邮箱已绑定");
                        return jsonObject.toJSONString();
                    }
                }else{
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", Code.USER_OP_FAIL);
                    jsonObject.put("msg", "该电话号已绑定");
                    return jsonObject.toJSONString();
                }
            }else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Code.USER_OP_FAIL);
                jsonObject.put("msg", "该用户ID已存在");
                return jsonObject.toJSONString();
            }
        }
        return "";
    }

    @GetMapping("/user/center")
    @ResponseBody
    public String getUserInfo(@RequestParam String id) {
        Student stu = userService.selectStudentById(id);
        Contacts con = contactsService.selectContactsById(stu.getContacts());
        Majority ma = majorityService.selectMajorityById(con.getMajority());
        ReturnData returnData = new ReturnData();
        returnData.setId(stu.getId());
        returnData.setName(stu.getName());
        returnData.setLoginTimes(stu.getLoginTimes());
        returnData.setLastLoginTime(Util.toRealTime(stu.getLastLoginTime()));
        returnData.setClassNum(con.getClassNum());
        returnData.setEntryYear(con.getEntryYear());
        returnData.setGraduateYear(con.getGraduateYear());
        returnData.setCity(con.getCity());
        returnData.setPhone(con.getPhone());
        returnData.setEmail(con.getEmail());
        returnData.setMajority(ma.getName());
        returnData.setEmployers(con.getEmployers());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", Code.USER_OP_SUCCESS);
        jsonObject.put("msg", "查找成功");
        jsonObject.put("data", returnData);
        return jsonObject.toJSONString();
    }

    @PostMapping("/user/update")
    public String updateUserData(HttpServletRequest request, Contacts contacts, String password, String name){
        String token = request.getHeader("Authorization").substring(7);
        String username = jwtUtil.parseToken(token).getBody().get("username", String.class);
        Student stu = userService.selectStudentById(username);
        Contacts con = contactsService.selectContactsById(stu.getContacts());
        JSONObject jsonObject = new JSONObject();
        if (!"".equals(name)) {
            stu.setName(name);
        }
        if (!"".equals(password)) {
            stu.setPassword(password);
        }
        if (!"".equals(contacts.getEmail())) {
            Contacts contacts1 = contactsService.selectByEmail(contacts.getEmail());
            if(contacts1 != null && !contacts1.getId().equals(con.getId())) {
                jsonObject.put("code", Code.USER_OP_FAIL);
                jsonObject.put("msg", "电子邮箱已存在");
            }
        }
        if (contacts.getPhone() != null) {
            Contacts contacts1= contactsService.selectByPhone(contacts.getPhone());
            if(contacts1 != null &&!contacts1.getId().equals(con.getId())) {
                jsonObject.put("code", Code.USER_OP_FAIL);
                jsonObject.put("msg", "电话号码已存在");
            }
        }
        if (contactsService.updateContacts(contacts, con, con.getId(), name, password) != 0
        && userService.updateStudent(stu) != 0) {
            jsonObject.put("code", Code.USER_OP_SUCCESS);
            jsonObject.put("msg", "更新成功");

        } else  {
            jsonObject.put("code", Code.USER_OP_SUCCESS);
            jsonObject.put("msg", "更新失败");
        }
        return jsonObject.toJSONString();
    }

    @GetMapping("/contacts/get/condition")
    public String selectByDim(Contacts contacts){
        Integer class_num=contacts.getClassNum() != null ? contacts.getClassNum() : -1;
        Integer entry_year= contacts.getEntryYear()!= null ? contacts.getEntryYear() : -1;
        Integer graduate_year= contacts.getGraduateYear()!= null ? contacts.getGraduateYear() : -1;
        String employers= contacts.getEmployers();
        String city=contacts.getCity();
        Integer majority=contacts.getMajority()!= null ? contacts.getMajority() : -1;
        String email=contacts.getEmail();
        Long phone= contacts.getPhone() != null? contacts.getPhone() : -1;


        List<Contacts> conList=contactsService.selectByDim(class_num,entry_year,graduate_year,employers,
                city, phone, email,majority);
        JSONObject jsonObject=new JSONObject();
        if(conList.isEmpty()){
            jsonObject.put("code",Code.USER_OP_DEFEATED);
            jsonObject.put("msg","没有符合条件的用户");
        }else{
            List<ReturnData> data=new ArrayList<>();
            for(Contacts contacts1:conList){
                ReturnData returnData=contactsService.selectById(contacts1.getId()+"");
                Majority majority1 = majorityService.selectMajorityById(contacts1.getMajority());
                returnData.setMajority(majority1.getName());
                data.add(returnData);
            }
            jsonObject.put("code",Code.USER_OP_SUCCESS);
            jsonObject.put("msg","查询成功");
            jsonObject.put("data",data);
        }

        return jsonObject.toJSONString();
    }

    @GetMapping("/contacts/get/name")
    public String selectByName(String name){
        JSONObject jsonObject=new JSONObject();
        List<ReturnData> data=contactsService.selectByName(name);
        for(ReturnData d:data){
            Majority majority1 = majorityService.selectMajorityById(Integer.parseInt(d.getMajority()));
            d.setMajority(majority1.getName());
        }
        if(data.isEmpty()){
            jsonObject.put("code",Code.USER_OP_DEFEATED);
            jsonObject.put("msg","没有符合条件的用户");
        }else{
            jsonObject.put("code",Code.USER_OP_SUCCESS);
            jsonObject.put("msg","查询成功");
            jsonObject.put("data",data);
        }
        return jsonObject.toJSONString();
    }

    @GetMapping("/contacts/get/all")
    public String selectAll(){
        JSONObject jsonObject=new JSONObject();
        List<ReturnData> data=contactsService.selectAll();
        for (ReturnData item: data) {
            String majority = majorityService.selectMajorityById(Integer.parseInt(item.getMajority())).getName();
            item.setMajority(majority);
        }
        if(data.isEmpty()){
            jsonObject.put("code",Code.USER_OP_DEFEATED);
            jsonObject.put("msg","查询失败，通讯录为空");
        }else{
            jsonObject.put("code",Code.USER_OP_SUCCESS);
            jsonObject.put("msg","查询成功");
            jsonObject.put("data",data);
        }
        return jsonObject.toJSONString();
    }

    @GetMapping("/contacts/count/majority")
    public String countByMajority() {
        List<Map<String, Object>> data =  userService.countByMajority();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", data);
        return jsonObject.toJSONString();
    }

    @GetMapping("/contacts/count/city")
    public String countByCity() {
        List<Map<String, Object>> data =  userService.countByCity();

        data.sort((o1, o2) -> {
            // 获取value键对应的值进行比较
            long value1 = (long) o1.get("value");
            long value2 = (long) o2.get("value");
            // 根据value进行降序排序
            return Long.compare(value2, value1);
        });
        data = data.subList(0, Math.min(10, data.size()));
        String[] names = new String[data.size()];
        long[] values = new long[data.size()];

        // 遍历列表，提取名称和值
        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> map = data.get(i);
            names[i] = (String) map.get("name");
            values[i] = (long) map.get("value");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("city", names);
        jsonObject.put("number", values);
        return jsonObject.toJSONString();
    }
}



